import React, { Component } from 'react';
import {StyleSheet, Text, View, TouchableOpacity, Image, ScrollView, StatusBar, TextInput, Keyboard} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Confirm from '../../../components/confirm/Confirm'
import { base } from "../../../assets/style";
import { API } from "../../../api";
import Toast from 'react-native-easy-toast'
import Loading from '../../../components/loading/index'
import ReactNativePickerSelect from "react-native-picker-select";
import { i18n } from "../../../utils/locales/i18n";

type Props = {};
export default class Buy extends Component<Props> {
	// static navigationOptions = {
	// 	title: i18n.t('i76') ,
	// 	headerBackTitle: null,
	// 	headerTintColor: '#0f0f0f',
	// };
	static navigationOptions = ({ navigation })  => {
		return {
			title:  navigation.state.params.seller.type === 2 ? i18n.t('i76') + 'FCC' : i18n.t('i82') + "FCC",
			headerBackTitle: null,
			headerTintColor: '#0f0f0f'
		}
	}
	constructor() {
		super();
		this.state = {
			buyValue: '',
			buyCount: '',
			modalVisible: false,
			seller: '',
			FCCCount: '0.00',
			HKDCount: '0.00',
			txBankId: '',
			loading: true,
			currentToastInfo: '',
			bankList: ''
		}
	}
	_initBankList = async () => {
		this.setState({
			loading: true
		})
		const res = await API._fetch('getBank', {}, 'GET')
		if (res.data.length > 0) {
			res.data.forEach(item => {
				item.label = item.Number
				item.value = item.Id
			})
			this.setState({
				bankList: res.data
			})
		}
		this.setState({
			loading: false
		})
	}
	componentWillMount(): void {
		// key: "33"
		// max: 9000
		// min: 100
		// name: "hello123"
		// price: 1
		// txRate: "86.36%"
		// txSum: 19
		// type: 1
		this._initBankList()
		this.setState({
			seller: this.props.navigation.state.params.seller || {
				key: "",
				max: 0,
				min: 0,
				id: '',
				name: "undefined",
				price: 0,
				txRate: "0%",
				txSum: 0,
				type: 0
			}
		})
	}


	// 修改HKD联动
	modifyHKD = (value) => {
		let HKDCount = value + ''
		let FCCCount = (Number(value) / Number(this.state.seller.price)).toFixed(6) + ''
		this.setState({
			HKDCount: HKDCount,
			FCCCount: FCCCount
		})
	}
	// 修改FCC联动
	modifyFCC = (value) => {
		let FCCCount = value + ''
		let HKDCount = (Number(value) * Number(this.state.seller.price)).toFixed(6) + ''
		this.setState({
			HKDCount: HKDCount,
			FCCCount: FCCCount
		})
	}

	// 订单确认处理逻辑
	handleConfirmOrder = async () => {
		this.setState({
			modalVisible: false
		})
		const reqData = {}
		reqData.id = this.state.seller.id
		reqData.amount = this.state.HKDCount
		// 2 购买 1 出售（需要银行卡）
		if (this.state.seller.type === 1) {
			if (!this.state.txBankId) {
				this.refs.toast.show(i18n.t('i83'))
				return
			}
			reqData.bankId = this.state.txBankId
		}
		const res = await API._fetch('placeOrder', reqData)
		// code: 10000
		// data: "b4c481f1a70d239c"
		// msg: "下单交易成功"
		if (res.code === 10000) {
			this.refs.toast.show(res.msg || i18n.t('o_success'))
			// 跳转到订单详情页
			setTimeout(() => {
				if (this.props.navigation.state.params.seller.type === 2) {
					// 购买
					this.props.navigation.navigate('BuyOrder', { orderNumber: res.data })
				} else {
					// 出售
					this.props.navigation.navigate('SellOrder', { orderNumber: res.data })
				}
			}, 20)
		} else {
			this.refs.toast.show(res.msg || i18n.t('o_defeat'))
		}
	}
	// 订单取消处理逻辑
	handleCancelOrder = () => {
		this.setState({
			modalVisible: false
		})
	}
	render() {
		return (
			<View style={{flex: 1, justifyContent: 'space-between', alignItems: 'center'}} onPress={() => Keyboard.dismiss()}>
				{/*toast*/}
				<Toast ref="toast" position='bottom' positionValue={200}/>
				{ this.state.loading ? (
					<Loading
						info={this.state.currentToastInfo}
					/>) : null }
				<StatusBar androidtranslucent='true'
						   backgroundColor="#fff"
						   barStyle="dark-content"/>
				<Confirm
					modalVisible={this.state.modalVisible}
					handleCancelOrder={this.handleCancelOrder}
					handleConfirmOrder={this.handleConfirmOrder}
					title={i18n.t('i84')}
					negative={i18n.t('cancel')}
					positive={i18n.t('confirm')}
				>
					<View style={{flex: 1, paddingVertical: 10}}>
						<View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center'}}>
							<Text style={{flex: 1, textAlign: 'center'}}>{i18n.t('i85')}</Text>
							<Text style={{flex: 1, textAlign: 'center'}}>{ this.state.seller.price } <Text style={{fontSize: 14}}>FCC/HKD</Text></Text>
						</View>
						<View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center'}}>
							<Text style={{flex: 1, textAlign: 'center'}}>{i18n.t('i86')}</Text>
							<Text style={{flex: 1, textAlign: 'center'}}>{ Number(this.state.FCCCount).toFixed(6) } FCC</Text>
						</View>
						<View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-around', alignItems: 'center'}}>
							<Text style={{flex: 1, textAlign: 'center'}}>{i18n.t('i87')}</Text>
							<Text style={{flex: 1, textAlign: 'center'}}>{ Number(this.state.HKDCount).toFixed(6) } HKD</Text>
						</View>
					</View>
				</Confirm>
				<View style={styles.bx}>
					{/*卡片*/}
					<TouchableOpacity style={{height: 170, width: '100%'}} onPress={() => Keyboard.dismiss()}>
						<LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 1}} colors={['#feac1c', '#ff7506']} style={{ height: '100%', borderRadius: 6, marginTop: 15, padding: 15}}>
							<View style={{flex: 1}}>
								<View style={{height: 70}}>
									<View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', }}>
										<Text style={{color: '#fff', fontSize: 20}}>{ this.state.seller.name }</Text>
										<Text style={{color: '#fff'}}>{ this.state.seller.price } FCC/HKD</Text>
									</View>
									<View style={{height: 30}}>
										<Text style={{color: '#fff', lineHeight: 30}}>{i18n.t('i88')}: { this.state.seller.min }~{ this.state.seller.max } HKD</Text>
									</View>
								</View>
								<View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-around' }}>
									<View style={{  paddingVertical: 10, justifyContent: 'space-around' }}>
										<Text style={{color: '#fff', textAlign: 'center'}}>{i18n.t('i89')}</Text>
										<Text style={{color: '#fff', textAlign: 'center'}}>{ this.state.seller.txSum }</Text>
									</View>
									<View style={{  paddingVertical: 10, justifyContent: 'space-around' }}>
										<Text style={{color: '#fff', textAlign: 'center'}}>{i18n.t('i90')}</Text>
										<Text style={{color: '#fff', textAlign: 'center'}}>{ this.state.seller.txRate }</Text>
									</View>
									{/*<View style={{  paddingVertical: 10, justifyContent: 'space-around' }}>*/}
									{/*<Text style={{color: '#fff', textAlign: 'center'}}>数额</Text>*/}
									{/*<Text style={{color: '#fff', textAlign: 'center'}}>988.23FCC</Text>*/}
									{/*</View>*/}
								</View>
							</View>
						</LinearGradient>
					</TouchableOpacity>
					{/*购买数量*/}
					<View>
						<TouchableOpacity style={{marginTop: 20}} onPress={() => Keyboard.dismiss()}>
							<Text style={[{fontSize: 20}, base.color_gray]}>{i18n.t('i91')}{this.props.navigation.state.params.seller.type === 2 ? i18n.t('i76') : i18n.t('i82')}{i18n.t('i92')} FCC？</Text>
						</TouchableOpacity>
						<TouchableOpacity onPress={() => Keyboard.dismiss()} style={{ flexDirection: 'row', justifyContent: 'flex-start', marginTop: 10 }}>
							<Text style={{color: '#ff7506'}}>{i18n.t('i88')}：</Text>
							<Text style={{color: '#ff7506'}}>{ this.state.seller.min } ~ { this.state.seller.max } HKD</Text>
						</TouchableOpacity>
						{/*输入框*/}
						<View style={{flexDirection: 'row', justifyContent: 'space-between', marginTop: 20}}>
							<View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around', width: '45%'}}>
								<Text>HKD</Text>
								<TextInput
									keyboardType={'numeric'}
									maxLength={16}
									underlineColorAndroid="transparent"
									placeholder={i18n.t('i86')}
									style={{height: 40, width: '70%', borderWidth: 0.5, borderColor: '#e5e5e5', color: '#808080', padding: 0, borderRadius: 5, paddingLeft: 10}}
									mutiline={false}
									clearTextOnFocus={true}
									onChangeText={(HKDCount) => this.modifyHKD(HKDCount)}
									value={this.state.HKDCount}/>
							</View>
							<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
								<Image style={{width: 20, height: 20}} source={require('../../../images/buy/switch.png')}/>
							</View>
							<View style={{flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around', width: '45%'}}>
								<Text>FCC</Text>
								<TextInput
									keyboardType={'numeric'}
									maxLength={16}
									clearTextOnFocus={true}
									underlineColorAndroid="transparent"
									placeholder={i18n.t('i86')}
									style={{height: 40, width: '70%', borderWidth: 0.5, borderColor: '#e5e5e5', color: '#808080', borderRadius: 5, paddingLeft: 10}}
									onChangeText={(FCCCount) => this.modifyFCC(FCCCount)}
									value={this.state.FCCCount}/>
							</View>
						</View>
						<View style={{paddingVertical: 10}}>
							{ this.state.seller.type === 2 ? (
								<Text style={{fontSize: 14, color: '#b3b3b3'}}>{ i18n.t('i93') }</Text>
							) : (
								<View style={{ height: 40, width: '100%', flexDirection: 'row', borderBottomWidth: 0, borderBottomColor: '#eee', justifyContent: 'space-between', alignItems: 'center', borderTopColor: '#eee', borderTopWidth: 0 }}>
									<View style={{ justifyContent: 'center', alignItems: 'center' }}>
										<Text style={{ color: '#0f0f0f', fontSize: 16 }}>{i18n.t('i94')}</Text>
									</View>
									<TouchableOpacity style={{ flex: 1, height: '100%', justifyContent: 'center' }}>
										<View style={{ width: '100%', flexDirection: 'row', justifyContent: 'flex-end' }}>
											<View style={{ flexDirection: 'row', alignItems: 'center', position: 'relative' }}>
												{this.state.bankList ? (
													<ReactNativePickerSelect
														style={{...pickerSelectStyles}}
														items={this.state.bankList}
														value={this.state.txBankId}
														hideIcon={true}
														placeholder={{
															label: i18n.t('i95'),
															value: null,
															color: '#9EA0A4',
														}}
														onValueChange={(txBankId) => {this.setState({txBankId})}}
													/>
												) : null}
												<Image resizeMode={'contain'} style={{width: 10, height: 10, position: 'absolute', top: '40%', right: 5}} source={require('@images/mine/icon_triangle.png')}/>
												{/*<Image style={{width: 10, height: 10}} source={require('../../../images/adver/arrow.png')}/>*/}
											</View>
										</View>
									</TouchableOpacity>
								</View>
							) }
						</View>
					</View>
				</View>
				{/*中部滚动*/}
				<View style={[{flex: 1, width: '100%', borderTopWidth: 10, borderColor: '#f2f2f2'}]}>
					<ScrollView>
						{/*常见问题*/}
						<View style={{justifyContent: 'center', alignItems: 'center'}}>
							<View style={[styles.bx]}>
								<View style={{paddingVertical: 10}}><Text style={[base.color_gray, {fontSize: 18}]}>{i18n.t('i96')}</Text></View>
								<View style={{paddingVertical: 5}}><Text style={[base.color_gray, styles.underlineStyle]}>{i18n.t('i97')}</Text></View>
								<View style={{paddingVertical: 5}}><Text style={[base.color_gray, styles.underlineStyle]}>{i18n.t('i98')}</Text></View>
							</View>
							{/*注意事项*/}
							{/*<View style={[styles.bx, {paddingTop: 20}]}>*/}
								{/*<View style={{paddingVertical: 10}}><Text style={{fontSize: 18}}>注意事项</Text></View>*/}
								{/*<View style={{paddingBottom: 20}}>*/}
									{/*<Text style={{fontSize: 14, color: '#aeaeae'}}>文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案文案</Text>*/}
								{/*</View>*/}
							{/*</View>*/}
						</View>
					</ScrollView>
				</View>
				{/*底部立即购买*/}
				<View style={{height: 50, width: '100%', backgroundColor: '#fff', flexDirection: 'row', justifyContent: 'space-between', borderTopColor: '#eee', borderTopWidth: 1}}>
					<View style={{flex: 1, paddingLeft: 10, justifyContent: 'center'}}>
						<View style={{flexDirection: 'row', alignItems: 'center'}}>
							<View><Text style={{color: '#808080'}}>{i18n.t('i99')}：</Text></View>
							<View><Text style={{color: '#ff7606'}}>{ (Number(this.state.HKDCount)).toFixed(6) }</Text></View>
							<View style={{paddingLeft: 5}}><Text style={{color: '#808080', fontSize: 12}}>HKD</Text></View>
						</View>
						<View style={{flexDirection: 'row', alignItems: 'center'}}>
							<View><Text style={{color: '#808080'}}>{i18n.t('i76')}：</Text></View>
							<View><Text style={{color: '#ff7606'}}>{(Number(this.state.FCCCount)).toFixed(6)}</Text></View>
							<View style={{paddingLeft: 5}}><Text style={{color: '#808080', fontSize: 12}}>FCC</Text></View>
						</View>
					</View>

					{
						( (Number(this.state.HKDCount) >= Number(this.state.seller.min)) &&
						(Number(this.state.HKDCount) <= Number(this.state.seller.max)) ) ?
							(
								<TouchableOpacity
									style={{width: '40%', backgroundColor: '#ff7606', justifyContent: 'center', alignItems: 'center'}}
									onPress={() => { this.setState({ modalVisible: true }) }}
								>
									<Text style={{ color: '#fff', fontSize: 16 }}>{i18n.t('submit')}</Text>
								</TouchableOpacity>
							) : (
								<TouchableOpacity
									style={{width: '40%', backgroundColor: '#b3b3b3', justifyContent: 'center', alignItems: 'center'}}
								>
									<Text style={{ color: '#fff', fontSize: 16 }}>{i18n.t('submit')}</Text>
								</TouchableOpacity>
							)

					}
				</View>
			</View>
		)
	}
}

const styles = StyleSheet.create({
	bx: {
		width: '95%'
	},
	underlineStyle: {
		lineHeight: 18,
		textDecorationLine: 'underline'
	}
});

const pickerSelectStyles = StyleSheet.create({
	inputIOS: {
		display: 'flex',
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		height: 40,
		paddingHorizontal: 10,
		borderWidth: 0,
		borderColor: '#d2d2d2',
		borderRadius: 5,
		borderBottomLeftRadius: 0,
		borderTopLeftRadius: 0,
		backgroundColor: 'white',
		color: '#808080',
		marginVertical: 5,
		paddingRight: 25
	},
	inputAndroid: {
		display: 'flex',
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		height: 40,
		width: 200,
		paddingHorizontal: 10,
		borderWidth: 0,
		borderColor: '#d2d2d2',
		borderRadius: 5,
		borderBottomLeftRadius: 0,
		borderTopLeftRadius: 0,
		backgroundColor: 'white',
		color: '#808080',
		marginVertical: 5,
		paddingRight: 25
	},
});
